<?php

namespace App\Libs\wrapper;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class User extends Comm
{
//////////////////////////////////////////////// 用户
////////////////////// 用户列表
    /**
     * 用户列表--数据
     * @param account 账号
     * @param email 邮箱
     * @param state 状态：1正常 2禁用
     * @apram create_time 创建时间
     * @param page 页码
     * @param page_count 每页条数
     */
    public function user_list($data)
    {
        $where = "1=1";
        //account 账号
        if (isset($data['account'])) {
            $where .= " and u.`account` like '%{$data['account']}%'";
        }
        //email 邮箱
        if (isset($data['email'])) {
            $where .= " and u.`email` like '%{$data['email']}%'";
        }
        //state 状态：1正常 2禁用
        if (isset($data['state'])) {
            $where .= " and u.`state`={$data['state']}";
        }
        //create_time 创建时间
        if (!empty($data['create_time'])) {
            $data['create_time'][1] = $data['create_time'][1] . ' 24:00:00';
            $where .= " and u.create_time>='{$data['create_time'][0]}' and create_time<='{$data['create_time'][1]}'";
        }
        //分页
        $limit = "";
        if ((!empty($data['page'])) and (!empty($data['page_count']))) {
            $limit = " limit " . ($data['page'] - 1) * $data['page_count'] . ",{$data['page_count']}";
        }

        $sql = "select SQL_CALC_FOUND_ROWS u.*, ifnull(r.role_name, '未绑定用色') as role_name
				       from users u
				       left join (select ruj.user_id, group_concat(distinct r.`name` order by r.Id asc separator ' | ') as role_name
				                         from xt_role_user_join ruj
				                         inner join xt_role r on r.Id = ruj.role_id
				                         group by ruj.user_id
				                  ) r on r.user_id = u.Id
				        where {$where}
				        order by u.Id desc {$limit}";
        $list = json_decode(json_encode(db::select($sql)), true);
        foreach ($list as $key=>$val){
           $user_organize = DB::table('organizes_member as a')->leftJoin('organizes as b','b.Id','=','a.organize_id')
                ->where('a.user_id',$val['Id'])->select('a.organize_id','b.name')->get();
           if(!empty($user_organize)){
               $list[$key]['organize_data'] = json_decode(json_encode($user_organize, true));
           }

        }
        //// 总条数
        if (isset($data['page']) and isset($data['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }
        $return['list'] = $list;
        return $return;
    }

    /**
     * 新增用户
     * @parma account 账号
     * @param password 密码
     * @paran phone 联系电话
     * @param sex 性别：1.男、2.女
     * @param email 邮箱
     */
    public function user_add($data)
    {
        //用户唯一性
        $sql = "select u.Id, u.state, m.Id as member_id
					from `users` u
					left join organizes_member m on m.organize_id={$data['organize_id']} and m.user_id=u.Id
					where u.account = '{$data['account']}'
					limit 1";
        $user_find = json_decode(json_encode(db::select($sql)), true);
        if (!empty($user_find)) {
            if ($user_find[0]['state'] == 2) {
                //修改用户状态
                $sql = "update users
							set `state`=1
							where `Id` = {$user_find[0]['Id']}";
                $update = db::update($sql);
                if ($update) {
                    return 2;
                } else {
                    return '修改用户状态失败';
                }
            }
        }

        db::beginTransaction();    //开启事务

        //新增用户
        if (empty($user_find)) {
            $arr = array();
            $arr['account'] = $data['account'];
            $arr['password'] = md5($data['password']);
            if (!empty($data['email'])) {
                $arr['email'] = $data['email'];
            }
            $arr['phone'] = $data['phone'];
            $arr['sex'] = $data['sex'];
            $arr['heard_img'] = 'http://q.zity.cn/headimg.jpg';
            $arr['create_time'] = date('Y-m-d H:i:s');
            $user_add = db::table('users')->insertGetId($arr);
            if (!$user_add) {
                db::rollback();    //事务回滚
                return '新增用户失败';
            }

            $user_id = $user_add;
        } else {
            $user_id = $user_find[0]['Id'];
        }
        if($data['organize_id']!=0){
            if (empty($user_find[0]['member_id'])) {
                // 新增成员数据
                $sql = "insert into organizes_member(`organize_id`, `user_id`, `create_time`)
						values ({$data['organize_id']}, {$user_id}, now())";
                $member_add = db::insert($sql);
                if (!$member_add) {
                    db::rollback();    //事务回滚
                    return '新增新增成员数据失败';
                }
            } else {
                // 编辑数
                $sql = "update organizes_member
						set organize_id={$data['organize_id']}
						where `Id` = {$user_find[0]['member_id']}";
                $member_update = db::update($sql);
                if (!$member_update) {
                    db::rollback();    //事务回滚
                    return '编辑成员数据失败';
                }
            }
        }
        db::commit();    //事物确认
        return 1;
    }

    /**
     * 部门新增成员
     * @parma user_id 用户id
     * @param organize_id 部门id
     */
    public function organize_add($data){
        if(!empty($data['user_id'])){
            foreach ($data['user_id'] as $val){
                $user_organize = DB::table('organizes_member as a')
                    ->leftJoin('users as u','a.user_id','=','u.Id')
                    ->leftJoin('organizes as b','a.organize_id','=','b.Id')
                    ->where('a.user_id',$val)->select('u.account','b.name')
                    ->first();
                if($user_organize){
                    return $user_organize->account.'已经在'.$user_organize->name;
                }else{
                    $organize_add = DB::table('organizes_member')->insert(['organize_id'=>$data['organize_id'],'user_id'=>$val,'create_time'=>now()]);
                    if($organize_add){
                        return 1;
                    }
                }
            }
        }else{
            return '请选择用户';
        }
    }

    /**
     * 编辑用户
     * @param Id 用户id
     * @param account 账号
     * @param password 密码
     * @param heard_img 头像
     * @param email 邮箱
     * @paran phone 联系电话
     * @param sex 性别：1.男、2.女
     * @param state 状态：1正常 2禁用
     */
    public function user_update($data)
    {
        //account 账号
        if (!empty($data['account'])) {
            //用户名唯一性
            $sql = "select `Id`, `state`
					from `users`
					where `account` = '{$data['account']}' and `Id`!={$data['Id']}";
            $user_find = json_decode(json_encode(db::select($sql)), true);
            if (!empty($user_find)) {
                if ($user_find[0]['state'] == 1) {
                    return '用户已存在';
                } else {
                    return "用户已存在，（{$data['account']}已被删除，可通过新增用户恢复正常）";
                }
            }
            $update['account'] = $data['account'];
        }
        //password 密码
        if (!empty($data['password'])) {
            $update['password'] = md5($data['password']);
        }
        //heard_img 头像
        if (!empty($data['heard_img'])) {
            $update['heard_img'] = $data['heard_img'];
        }
        //email 邮箱
        if (!empty($data['email'])) {
            $update['email'] = $data['email'];
        }
        //phone 联系电话
        if (!empty($data['phone'])) {
            $update['phone'] = $data['phone'];
        }
        //sex 性别：1.男、2.女
        if (!empty($data['sex'])) {
            $update['sex'] = $data['sex'];
        }
        //state 状态：1正常 2禁用
        if (!empty($data['state'])) {
            $update['state'] = $data['state'];
        }

        if (!empty($data['organize_id'])) {
           $om = db::table('organizes_member')->where('user_id',$data['Id'])->first();
           if($om){
            db::table('organizes_member')->where('user_id',$data['Id'])->update(['organize_ids'=>$data['organize_id'],'organize_id'=>$data['organize_id']]);
           }else{
            db::table('organizes_member')->insert(['organize_ids'=>$data['organize_id'],'organize_id'=>$data['organize_id'],'user_id'=>$data['Id'],'type'=>3,'create_time'=>date('Y-m-d H:i:s',time())]);
           }

          
        }

        $up = DB::table('users')->where('Id',$data['Id'])->update($update);
        
        if ($up !== false) {
            Redis::Hdel('users',$data['Id']);
            return 1;
        } else {
            return '操作失败';
        }
    }

    /**
     * 修改用户角色
     * @param user_id 用户id
     * @param id_del 删除角色id  例如：1,2,3
     * @param id_add 新增角色id  例如：1,2,3
     */
    public function user_role_update($data)
    {
        db::beginTransaction();    //开启事务

        //删除用户角色
        if (!empty($data['id_del'])) {
            $sql = "delete
						from xt_role_user_join
						where user_id={$data['user_id']} and role_id in ({$data['id_del']})";
            $del = db::delete($sql);
            if (!$del) {
                db::rollback();    //事务回滚
                return '删除用户角色失败';
            }
        }

        //新增用户角色
        if (!empty($data['id_add'])) {
            $insert = '';
            $id_add = explode(',', $data['id_add']);
            foreach ($id_add as $v) {
                $insert .= ",({$data['user_id']}, {$v})";
            }
            $insert = substr($insert, 1);

            $sql = "insert into xt_role_user_join(`user_id`, `role_id`) values {$insert}";
            $add = db::insert($sql);
            if (!$add) {
                db::rollback();    //事务回滚
                return '删除用户角色失败';
            }
        }

        db::commit();//确认事务
        return 1;
    }

////////////////////// 个人中心

    /**
     * 编辑消息
     * @param Id 用户id
     */
    public function tiding_update($data)
    {
        $field_arr = array('user_fs', 'user_js', 'title', 'content', 'is_read');
        $set = '';
        foreach ($data as $k => $v) {
            if (in_array($k, $field_arr)) {
                $set .= ",`{$k}`='{$v}'";
            }
        }
        $set = substr($set, 1);

        $sql = "update tidings
					set {$set}
					where `Id` = {$data['Id']}";
        $update = db::update($sql);
        if ($update !== false) {
            Redis::HDEL('tiding:'.$data['user_info']['Id'],$data['Id']);
            return 1;
        } else {
            return '编辑失败';
        }
    }

    /**
     * 修改密码
     * @param password_log 旧密码
     * @param password_new 新密码
     */
    public function password_update($data)
    {

        $user_id = $data['user_info']['Id'];
        //旧密码是否正确
        $sql = "select `Id`
                    from users
                    where Id = {$user_id} and password='" . md5($data['password_log']) . "'";
        $user_find = json_decode(json_encode(db::select($sql)), true);
        if (empty($user_find)) {
            return '旧密码错误';
        }

        //修改密码
        $sql = "update users
					set `password`='" . md5($data['password_new']) . "'
					where `Id` = {$user_id}";
//        var_dump($sql);die;

        $update = db::update($sql);
        if ($update !== false) {
            return 1;
        } else {
            return '操作失败';
        }
    }


}//结束符